import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Pdf2String {
    // PDF文件路径
    private static final String inputFilePath = "C:/Users/hongz/Desktop/pdf/二标段 （车票名单）.pdf";
    // 输出Word文件路径
    private static final String outputFolder = "C:/Users/hongz/Desktop/pdf/";
    // 文件名称
    private final static File file = new File(inputFilePath);

    public static void main(String[] args) {
        try {
            // 创建一个PDF解析器
            PDFParser pdfParser = new PDFParser();
            // 设置ContentHandler
            ContentHandler contentHandler = new BodyContentHandler();
            Metadata metadata = new Metadata();
            ParseContext parseContext = new ParseContext();
            // 解析PDF
            pdfParser.parse(new FileInputStream(inputFilePath), contentHandler, metadata, parseContext);
            // 获取文本内容
            String content = contentHandler.toString();
            // 将内容写入Word文档
            try (OutputStream outputStream = new FileOutputStream(outputFolder + file.getName().replace(".pdf", "") + ".docx");
                 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
                outputStreamWriter.write(content);
            }
            System.out.println("PDF转换为Word成功！");
        } catch (IOException | SAXException | TikaException e) {
            System.err.println("转换过程中发生错误：" + e.getMessage());
        }
    }
}
